package gdut.jmxywz.daoImpl;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import gdut.jmxywz.dao.CommonDAO;
import gdut.jmxywz.util.PageModel;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.ServletContext;

import org.apache.struts2.ServletActionContext;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class CommonDAOImpl extends HibernateDaoSupport implements CommonDAO {

	public boolean deleteObject(Object obj) {
		// TODO Auto-generated method stub
		try {
			this.getHibernateTemplate().delete(obj);
			return true;
		}catch(Exception e){
			 e.printStackTrace();
			return false;
		}
		
	}
	
	public Object findByIntId(int id,String className){
		Object object = null;
		Object obj = null;
		try {
			Class<?> c= Class.forName(className);
			try {
				obj = c.newInstance();
			} catch (InstantiationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		object = this.getHibernateTemplate().get(obj.getClass(), id);
		return object;
	}
	

	public Object findByStringId(String id, String className) {
		Object object = null;
		Object obj = null;
		try {
			Class<?> c= Class.forName(className);
			try {
				obj = c.newInstance();
			} catch (InstantiationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		object = this.getHibernateTemplate().get(obj.getClass(), id);
		return object;
	}

	@SuppressWarnings("unchecked")
	public List findListByHql(String hql, Object[] parem) {
		// TODO Auto-generated method stub
		
		return this.getHibernateTemplate().find(hql,parem);
	}

	@SuppressWarnings("unchecked")
	public PageModel findPage(String hql, Object[] parem, int currentPage,
			int pageSize,String nextPage,String search_parameter) {
		// TODO Auto-generated method stub
		PageModel pm = new PageModel();
		List listTotal = this.getHibernateTemplate().find(hql);
		
		System.out.println("--dao--"+search_parameter);
		if(!listTotal.isEmpty()){
			int offset=(currentPage-1)*pageSize; //算出当前页的第一条记录
			List listLimit = this.getSession().createQuery(hql).setFirstResult(offset).setMaxResults(pageSize).list();
			//---
			
			if(listLimit.isEmpty()){
				currentPage=currentPage-1;
				offset = (currentPage-1)*pageSize;
				listLimit = this.getSession().createQuery(hql).setFirstResult(offset).setMaxResults(pageSize).list();				
				
			}
			int totalPage = listTotal.size()/pageSize; //计算总页数
			
			if(listTotal.size()%pageSize!=0){
				totalPage =totalPage+1;
			}
			
			
			StringBuffer pageinfo = new StringBuffer("");
			

			pageinfo = pageinfo.append("共有" + listTotal.size() + "条记录     分"
					+ totalPage + "页显示");
			pageinfo = pageinfo.append("  当前第 " + currentPage + " 页");
			pageinfo = pageinfo.append("<br/>");

			if (currentPage <= 1)
				pageinfo = pageinfo.append("  第一页   上一页");
			else {
				System.out.println("------上一页-----------"+search_parameter);
				pageinfo = pageinfo.append("  <a href=\"" + nextPage
						+ "?currentPage=1"+search_parameter+"\">第一页</a>");
				pageinfo = pageinfo.append("  <a href=\"" + nextPage
						+ "?currentPage=" + (currentPage - 1)
						+search_parameter+ "\">上一页</a>");
			}

			int last4Page = currentPage;
			int top4Page = currentPage;
			int pageLimit=4;
			// ///////////计算前四页/////////////////////
			if (currentPage - pageLimit > 0) {
				top4Page = currentPage - pageLimit;
			} else {
				top4Page = 1;
			}
			// ///////////计算后四页/////////////////////
			if (currentPage + pageLimit < totalPage) {
				last4Page = currentPage + pageLimit;
			} else {
				last4Page = totalPage;
			}

			for (int i = top4Page; i < currentPage; i++) {
				System.out.println("------第-----------"+i+"----页---"+search_parameter);
				pageinfo = pageinfo.append("&nbsp;<a href=\"" + nextPage
						+ "?currentPage=" + i+search_parameter + "\">[" + i + "]</a>");
			}

			pageinfo = pageinfo.append("&nbsp;" + currentPage + "&nbsp;");
			for (int i = currentPage + 1; i <= last4Page; i++) {
				pageinfo = pageinfo.append("&nbsp;<a href=\"" + nextPage
						+ "?currentPage=" + i+search_parameter + "\">[" + i + "]</a>");
			}

			if (currentPage < totalPage) {
				pageinfo = pageinfo.append("&nbsp;<a href=\"" + nextPage
						+ "?currentPage=" + (currentPage + 1)+search_parameter
						+ "\">下一页</a>");
				pageinfo = pageinfo.append("&nbsp;<a href=\"" + nextPage
						+ "?currentPage=" + totalPage+search_parameter + "\">最后一页</a>");
			} else {

				pageinfo = pageinfo.append("&nbsp;下一页&nbsp;最后一页");
			}


			String pageMessage=pageinfo.toString().replaceAll("&\\?", "&");
			
			//System.out.print("-------------------------"+listTotal.size()+listLimit.size()+"------------------------");
			
			pm.setCurrentPage(currentPage);
			pm.setTotalCount(listTotal.size());
			pm.setList(listLimit);
			pm.setTotalPage(totalPage);
			pm.setPageMessage(pageMessage);
			
		}
		
		return pm;
	}

 
		/**
		 * @说明 此方法用于查询并分页
		 * @param 需要hql语句和object对象参数和当前页currentPage和每页记录数pageSize
		 * @return 成功执行返回pm
		 * */
		public PageModel splitByList(String hql, Object[] parem, int currentPage, int pageSize) {
			PageModel pm = new PageModel();
			List listTotal = this.getHibernateTemplate().find(hql);
			if (!listTotal.isEmpty()) {
				int offset = (currentPage - 1) * pageSize;// 算出当前页的第一条记录			
				List listLimit = this.getSession().createQuery(hql).setFirstResult(offset).setMaxResults(pageSize).list();
				if (listLimit.isEmpty()) {
					currentPage = currentPage - 1;
					offset = (currentPage - 1) * pageSize;
					listLimit = this.getSession().createQuery(hql).setFirstResult(
							offset).setMaxResults(pageSize).list();
				}
				int totalPage = listTotal.size() / pageSize;// 总页数
				if (listTotal.size() % pageSize != 0) {// 有余数，总页数加1
					totalPage = totalPage + 1;
				}
				pm.setCurrentPage(currentPage);
				pm.setTotalCount(listTotal.size());
				pm.setList(listLimit);
				pm.setTotalPage(totalPage);
			}
			
			return pm;
		}
	
	
	
	
	public boolean saveObject(Object obj) {
		// TODO Auto-generated method stub
	 try{
		
		 this.getHibernateTemplate().save(obj);
		 return true ;
	 }catch(Exception e){
		 e.printStackTrace();
		 return false;

	 }
	}

	public boolean updateObject(Object obj) {
		// TODO Auto-generated method stub
		try {
			this.getHibernateTemplate().update(obj);
			return true ;
		}catch(Exception e){
			 e.printStackTrace();
		return false;
		}
	}

	
	
	
	
	/***
	 * 网站静态化方法
	 */
	public void createHtml(ServletContext context, Map<String, Object> data,
			String templatePath, String targetHtmlPath) {
		// TODO Auto-generated method stub
		
		Configuration freemarkerCfg  = new Configuration();
		
//		String path="D:/Program Files/Apache Software Foundation/Apache2.2/htdocs/jmxywz/";
		String path=ServletActionContext.getRequest().getRealPath("/")+"/";
		System.out.println("context "+context);
		
		//加载模板
		freemarkerCfg.setServletContextForTemplateLoading(context, "/");
		
		freemarkerCfg.setEncoding(Locale.getDefault(), "gbk");
		
		try {
			//指定模板路径
			Template template  = freemarkerCfg.getTemplate(templatePath, "gbk");
			
			template.setEncoding("gbk");
			
			//静态页面路径
			String htmlPath = path+targetHtmlPath;
			
			File htmlFile = new File(htmlPath);
			
			Writer out = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(htmlFile),"gbk"));
		
			try {
				//处理模板
				template.process(data, out);
				out.flush();
				out.close();
				
			} catch (TemplateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}

	public boolean createDirs(String parentDir, String subDir) {
		// TODO Auto-generated method stub
		return false;
	}

	public boolean fileDelete(String url) {
		// TODO Auto-generated method stub
		url = ServletActionContext.getRequest().getRealPath(url);
		
		File file = new File(url);
		
		if(file.exists()){
			
			try {
				file.delete();
				
			} catch (Exception e) {
				
				System.out.println("=文件删除不成功！=");
				e.printStackTrace();
				
				return false;
			}
			
			return true;
		}
		else{
			
			System.out.println("----fileurl-----"+url);
			return false;
		}
		
		
	}

	public boolean fileExist(String url) {
		// TODO Auto-generated method stub
		
		url = ServletActionContext.getRequest().getRealPath(url);
		
		File file = new File(url);
		
		if(file.exists()){
			
			return true;
		}
		else{
			
			System.out.println("----fileurl-----"+url);
			return false;
		}
	}
	/***
	 * 静态页面分页
	 * @param hql
	 * @param currentPage
	 * @param nextPage
	 * @param pageSize
	 * @return
	 */
	public PageModel findHtmlPage(String hql,  int currentPage,String infoType,int pageSize) {
		// TODO Auto-generated method stub
		PageModel pm = new PageModel();
		List listTotal = this.getHibernateTemplate().find(hql);
		
		if(!listTotal.isEmpty()){
			int offset=(currentPage-1)*pageSize; //算出当前页的第一条记录
			List listLimit = this.getSession().createQuery(hql).setFirstResult(offset).setMaxResults(pageSize).list();
			//---
			
			if(listLimit.isEmpty()){
				currentPage=currentPage-1;
				offset = (currentPage-1)*pageSize;
				listLimit = this.getSession().createQuery(hql).setFirstResult(offset).setMaxResults(pageSize).list();				
				
			}
			int totalPage = listTotal.size()/pageSize; //计算总页数,生成totalPage个html页面。
			
			if(listTotal.size()%pageSize!=0){
				totalPage =totalPage+1;
			}
		
			
			
			StringBuffer pageinfo = new StringBuffer("");
			

			pageinfo = pageinfo.append("共有" + listTotal.size() + "条记录     分"
					+ totalPage + "页显示");
			pageinfo = pageinfo.append("  当前第 " + currentPage + " 页");
			pageinfo = pageinfo.append("<br/>");

			if (currentPage <= 1)
				pageinfo = pageinfo.append("  第一页   上一页");
			else {
				System.out.println("------上一页-----------");
				pageinfo = pageinfo.append("  <a href=\""+infoType+"List1.html"
					                       +"\">第一页</a>");
				pageinfo = pageinfo.append("  <a href=\"" +infoType+"List"+(currentPage - 1)+".html"
						
						+ "\">上一页</a>");
			}

			int last4Page = currentPage;
			int top4Page = currentPage;
			int pageLimit=4;
			// ///////////计算前四页/////////////////////
			if (currentPage - pageLimit > 0) {
				top4Page = currentPage - pageLimit;
			} else {
				top4Page = 1;
			}
			// ///////////计算后四页/////////////////////
			if (currentPage + pageLimit < totalPage) {
				last4Page = currentPage + pageLimit;
			} else {
				last4Page = totalPage;
			}

			for (int i = top4Page; i < currentPage; i++) {
				System.out.println("------第-----------"+i+"----页---");
				pageinfo = pageinfo.append("&nbsp;<a href=\"" +infoType+"List"+i+".html"
						      + "\">[" + i + "]</a>");
			}

			pageinfo = pageinfo.append("&nbsp;" + currentPage + "&nbsp;");
			for (int i = currentPage + 1; i <= last4Page; i++) {
				pageinfo = pageinfo.append("&nbsp;<a href=\"" +infoType+"List"+i+".html"
						    + "\">[" + i + "]</a>");
			}

			if (currentPage < totalPage) {
				pageinfo = pageinfo.append("&nbsp;<a href=\"" +infoType+"List"+(currentPage +1 )+".html"
						+ "\">下一页</a>");
				pageinfo = pageinfo.append("&nbsp;<a href=\"" +infoType+"List"+totalPage+".html"
						 + "\">最后一页</a>");
			} else {

				pageinfo = pageinfo.append("&nbsp;下一页&nbsp;最后一页");
			}


			String pageMessage=pageinfo.toString().replaceAll("&\\?", "&");
			
			//System.out.print("-------------------------"+listTotal.size()+listLimit.size()+"------------------------");
			
			pm.setCurrentPage(currentPage);
			pm.setTotalCount(listTotal.size());
			pm.setList(listLimit);
			pm.setTotalPage(totalPage);
			pm.setPageMessage(pageMessage);
			
		}
		
		return pm;
	}

}
